const record = require("../models/records")
const point = require('../models/point')
const question = require('../models/question')
const menu = require('../models/menu')
const user = require('../models/userDetail')

var express = require('express');
var async = require('async');  //async module
var router = express.Router();

const formidable = require('formidable');

//返回图片
router.post('/', (req, res, next) => {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
            let nowTime = new Date();
            if(fields.period === "0") {
                nowTime.setDate(nowTime.getDate()-7);
                nowTime.setHours(0,0,0,0);
            }else if(fields.period === "1"){
                nowTime.setMonth(nowTime.getMonth()-3);
                nowTime.setHours(0,0,0,0);
            }else {
                nowTime.setFullYear(2010);
            }
            var formatDate = function (date) {
                var y = date.getFullYear();
                var m = date.getMonth() + 1;
                m = m < 10 ? ('0' + m) : m;
                var d = date.getDate();
                d = d < 10 ? ('0' + d) : d;
                var h = date.getHours();
                h=h < 10 ? ('0' + h) : h;
                var minute = date.getMinutes();
                minute = minute < 10 ? ('0' + minute) : minute;
                var second=date.getSeconds();
                second=second < 10 ? ('0' + second) : second;
                return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
            }

            var find_point = (point_id) => {
                return new Promise(function (resolve, reject) {
                    point.findOne({
                        _id: point_id
                    }, (err, doc) => {
                        if(err) {
                            res.json({'state': false, 'msg': err})
                        }else {
                            resolve(doc);
                        }
                    })
                })
            }

            var find_question = (question_id) => {
                return new Promise(function (resolve, reject) {
                    question.findOne({
                        _id: question_id
                    }, (err, doc) => {
                        if(err) {
                            res.json({'state': false, 'msg': err})
                        }else {
                            resolve(doc);
                        }
                    })
                })
            }

            var find_menu = () => {
                return new Promise(function (resolve, reject) {
                    menu.find({}, (err, doc) => {
                        if(err) {
                            res.json({'state': false, 'msg': err})
                        }else {
                            for(var i=0;i<doc.length;i++) {
                                if(doc[i].lesson === 'js') {
                                    var js = i;
                                }else if(doc[i].lesson === 'wx'){
                                    var wx = i;
                                }else if(doc[i].lesson === 'ydhlw'){
                                    var ydhlw = i;
                                }
                            }
                            let menus = {
                                'js': doc[js],
                                'wx': doc[wx],
                                'ydhlw': doc[ydhlw]
                            }
                            resolve(menus)
                        }
                    })
                })
            }

            var lesson_name = {
                'js': 'JavaScript',
                'wx': '微信小程序',
                'ydhlw': '移动互联网'
            }

            var return_data = (menus) => {
                user.findOne({
                    stuNo: fields.stuNo,
                    school: fields.school
                }, (err, stu) => {
                    if(err) {
                        res.json({'state': false, 'msg': err})
                    }else {
                        if(stu){
                            pageQueryNew(
                                fields.page, 
                                fields.count, 
                                record, 
                                {UUID: stu.UUID}, 
                                {time: fields.reverse}, 
                                async (err, result) => {
                                    if(err) {
                                        res.json({'state': false, 'msg': err})
                                    }else {
                                        const {data: records, count} = result;
                                        let QuesPath = [];
                                        for(var i=0;i<records.length;i++) {
                                            if(records[i].time) {
                                                if(records[i].time>=nowTime) {
                                                    let tmp_ques = {};
                                                    let lesson = records[i].menu.split(',');
                                                    if(records[i].attachment === true) {
                                                        let point = await find_point(records[i].point_ID);
                                                        tmp_ques = {
                                                            lesson: lesson_name[lesson[0]],
                                                            char_name: menus[lesson[0]].menu[lesson[1]].title,
                                                            section_name: menus[lesson[0]].menu[lesson[1]].subtitle[lesson[2]],
                                                            point_id: records[i].point_ID,
                                                            question_id: records[i].question_ID,
                                                            attachment: true,
                                                            point_title: point.title,
                                                            question_content: point.practice.question_editor_Content,
                                                            question_item: point.practice.items,
                                                            question_type: point.practice.type,
                                                            question_answer: point.practice.answer,
                                                            question_illustration: point.practice.illustrationContent,
                                                            bloom: point.bloom,
                                                            stu_answer: records[i].stu_answer,
                                                            result: records[i].result,
                                                            time: formatDate(new Date(new Date(records[i].time)+(8*60*60*1000)))
                                                        };
                                                        QuesPath.push(tmp_ques);
                                                    }else {
                                                        let point = await find_point(records[i].point_ID);
                                                        let question = await find_question(records[i].question_ID);
                                                        if(question){
                                                            tmp_ques = {
                                                                lesson: lesson_name[lesson[0]],
                                                                char_name: menus[lesson[0]].menu[lesson[1]].title,
                                                                section_name: menus[lesson[0]].menu[lesson[1]].subtitle[lesson[2]],
                                                                point_title: point.title,
                                                                question_content: question.question,
                                                                point_id: records[i].point_ID,
                                                                question_id: records[i].question_ID,
                                                                attachment: false,
                                                                question_item: question.items,
                                                                question_type: question.type,
                                                                question_answer: question.answer,
                                                                question_illustration: question.illustrationContent,
                                                                bloom: question.bloom,
                                                                stu_answer: records[i].stu_answer,
                                                                result: records[i].result,
                                                                time: formatDate(new Date(new Date(records[i].time)+(8*60*60*1000)))
                                                            };
                                                            QuesPath.push(tmp_ques);
                                                        } 
                                                    }
                                                }
                                            }
                                        }
                                        res.json({
                                            'state': true,
                                            'QuesPath': QuesPath
                                        })
                                    }
                                })
                        }else {
                            res.json({
                                'state':false,
                                'msg': '未找到相应学生！'
                            })
                        }
                    }
                })
            }
            find_menu().then(return_data);
        }

    });

});

module.exports = router;


/**

* 分页查询，该方法依赖`mongoose`组件

* @param page 页数，如第1页，就传1

* @param pageSize 每页大小，如一页展示10条，就传10

* @param Model mongoose的指定Model对象，是一个schema对象

* @param fieldJson 查询字段

* @param populate 关联查询

* @param queryParams 查询条件

* @param sortParams 排序

* @param callback 回调函数

*/

function pageQueryNew(page, pageSize, Model,  queryParams, sortParams, callback) {

    var start = (page -1) * pageSize;

    var $page = {};

    async.parallel(
        {

            count:function (done) {// 查询数量

                Model.count(queryParams).exec(function (err, count) {

                    done(err, count);

                });

            },

            records:function (done) {   // 查询一页的记录

                Model.find(queryParams).skip(start).sort(sortParams).limit(pageSize).exec(function (err, doc) {

                    done(err, doc);

                });

            }

        }, function (err, results) {

            var count = results.count;

            $page.total = count;

            $page.data = results.records;

            callback(err, $page);

        }
    );

}